package com.xyy.yueshijia.shopping;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.xyy.yueshijia.MainActivity;
import com.xyy.yueshijia.R;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    //mob三方库
    String APPKEY = "1b1f2e138bf3c";
    String APPSECRETE = "07aaf34c3465755d86fbff43b05593af";

    //电话号码输入框
    private EditText mPhoneEdt;

    //public Context context;
    //验证码输入框
    private EditText mCodeEdt;
    //发送验证码按钮
    private Button mCodeRequestBtn;
    //注册按钮
    private Button mRegisterBtn;

    private int i = 60;
    private ImageView mImageView;
    private UMShareAPI umShareAPI;
    private FragmentManager fm;
    private FragmentTransaction shiwu;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_register);

        //友盟分享
       umShareAPI = UMShareAPI.get(this);
        //PlatformConfig.setSinaWeibo("1982598855", "ae082610110b61507f1d5c401120d0d3");
       // PlatformConfig.setSinaWeibo("1982598855", "af8ee0049f17a55215f882e4120deb6a");
          PlatformConfig.setSinaWeibo("3592935669", "d6d85647e5fabb71052fe77aacf96927");
        Config.DEBUG = true;
        Config.REDIRECT_URL = "http://sns.whalecloud.com/sina2/callback";

        init();

        mImageView = (ImageView) findViewById(R.id.shop_weibo2);
        mImageView.setOnClickListener(this);
        findViewById(R.id.shop_register_usepassword).setOnClickListener(this);
        findViewById(R.id.shop_register_back).setOnClickListener(this);

    }


    /**
     * 短息初始化控件
     */
    private void init() {
        mPhoneEdt = (EditText) findViewById(R.id.shop_register_phone);
        mCodeEdt = (EditText) findViewById(R.id.shop_et_yanzhengma);
        mCodeRequestBtn = (Button) findViewById(R.id.shop_yanzhengma_button);
        mRegisterBtn = (Button) findViewById(R.id.shop_register_btn);

        mCodeRequestBtn.setOnClickListener(this);
        mRegisterBtn.setOnClickListener(this);
        //短信SDK
        SMSSDK.initSDK(this, APPKEY, APPSECRETE);
        EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int i, int i1, Object o) {
                Message message = new Message();
                message.arg1 = i;
                message.arg2 = i1;
                message.obj = o;
                handler.sendMessage(message);
            }
        };
        //短信注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);
    }

    @Override
    public void onClick(View view) {
        String mIphone = mPhoneEdt.getText().toString();
        switch (view.getId()) {
            //注册页微博登陆
            case R.id.shop_weibo2:
                //友盟分享, 获得微博数据
                umShareAPI.getPlatformInfo(RegisterActivity.this, SHARE_MEDIA.SINA, new UMAuthListener() {
                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

                        Toast.makeText(RegisterActivity.this, "控制台已经获得数据", Toast.LENGTH_SHORT).show();
                        Set<Map.Entry<String, String>> entries = map.entrySet();
                        for (Map.Entry<String, String> entry : entries) {
                            Log.e("========", "key:" + entry.getKey() + ",value:" + entry.getValue());
                        }
                        Iterator<Map.Entry<String, String>> it = entries.iterator();
                        while (it.hasNext()) {
                            Map.Entry<String, String> mey = it.next();
                            String key = mey.getKey();
                            String value = mey.getValue();
                            if (key.equals("name")) {
                                Log.e("------", "name:" + value);
                                // Glide.with(context).load(value).into(myImageHead);
                                // mHeadName.setText(value);

                                Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                                intent.putExtra("grxx", 1);
                                intent.putExtra("name", value);
                                startActivity(intent);
                                finish();

                                //  FragmentTransaction transaction = getFragmentManager().beginTransaction();
                                //   FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

                                //   transaction.replace(R.id.main_frame_layout, new MyFragment());

                                //   transaction.commit();


                                //    startActivity(intent);
                                //  FragmentManager manager = getFragmentManager();
                                //   shiwu = fm.beginTransaction();
                                //      MyFragment myfragment =new MyFragment();
                                //      Bundle bundle=new Bundle();
                                //      bundle.putString("name",value);
                                //      myfragment.setArguments(bundle);

                                //    shiwu.replace(R.id.coordinator, myfragment);

                                //   shiwu.commit();
                                break;

                            }else {
                                Toast.makeText(RegisterActivity.this, "name未传值", Toast.LENGTH_SHORT).show();
                                break;
                            }
                        }


                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {

                    }
                });


                break;
            //验证码倒计时button
            case R.id.shop_yanzhengma_button:
                if (judgePhoneNums(mIphone)) {
                    SMSSDK.getVerificationCode("86", mIphone);
                    mCodeRequestBtn.setClickable(false);
                    mCodeRequestBtn.setText("重新发送(" + i + ")");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (; i > 0; i--) {
                                handler.sendEmptyMessage(1);
                                if (i <= 0) {
                                    break;
                                }
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            handler.sendEmptyMessage(2);
                        }
                    }).start();
                } else {
                }
                break;
            case R.id.shop_register_btn:
                SMSSDK.submitVerificationCode("86", mIphone, mCodeEdt.getText().toString());
                break;
            //注册页,的密码登陆,跳到登陆页
            case R.id.shop_register_usepassword:
                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(intent);
                break;
                //注册页返回主页
            case R.id.shop_register_back:
                Intent register_mainty = new Intent(RegisterActivity.this, MainActivity.class);
                startActivity(register_mainty);



        }
    }

    /**
     * 判断手机号码是否合理
     *
     * @paramphoneNums
     */
    private boolean judgePhoneNums(String phoneNums) {
        if (isMatchLength(phoneNums, 11)
                && isMobileNO(phoneNums)) {
            return true;
        }
        Toast.makeText(this, "手机号码输入有误！", Toast.LENGTH_SHORT).show();
        return false;
    }

    /**
     * 判断一个字符串的位数
     *
     * @return
     * @paramstr
     * @paramlength
     */
    public static boolean isMatchLength(String str, int length) {
        if (str.isEmpty()) {
            return false;
        } else {
            return str.length() == length ? true : false;
        }
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobileNums) {
        String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。

        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                mCodeRequestBtn.setText("重新发送" + i + "s");
            } else if (msg.what == 2) {
                mCodeRequestBtn.setText("获取验证码");
                mCodeRequestBtn.setClickable(true);
            } else {

                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;

                Log.e("event", "event=" + event);
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                        Toast.makeText(getApplicationContext(), "提交验证码成功",
                                Toast.LENGTH_SHORT).show();

                        Intent intent = new Intent(RegisterActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {

                        //获取验证码成功
                        Toast.makeText(getApplicationContext(), "正在获取验证码",
                                Toast.LENGTH_SHORT).show();
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        //返回支持发送验证码的国家列表
                    }
                }
            }
        }
    };


    //友盟分享
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        //mob三方
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();
    }
}
